/*
导出excel  可以自定义 表格信息
*/

import fileSaver from "file-saver";
import excel from "exceljs";

import { Message } from "element-ui";

import { toBase64 } from "./util";

export default function exportDataInExcel(list, name, width, nameList) {
  /*
  接收的参数
  list:数据列表 []
  name:表格名字 ''
  width:每个字段显示的宽度 []
  nameList:每个字段的名字 []
  */

  Message.success("开始导出...");
  // 初始化表格信息
  const workbook = new excel.Workbook();
  workbook.creator = "";
  workbook.lastModifiedBy = "";
  workbook.created = new Date();
  workbook.modified = new Date();
  workbook.lastPrinted = new Date();
  const sheet = workbook.addWorksheet(name);

  // 初始
  const columnWidth = width; // 列宽
  const arr = nameList;
  let infoColumnNum = arr.length;
  sheet.getRow(3).values = arr;
  // 标题栏
  sheet.mergeCells(1, 1, 2, infoColumnNum);
  sheet.getCell("A1").value = `${name}(${list.length})`;
  sheet.getCell("A1").fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFFCE4D6" }
  };
  sheet.getCell("A1").font = {
    color: { argb: "FFFF0000" },
    size: 14,
    bold: true
  };

  list.forEach((el, index) => {
    // 获取到每个对象字段的[]值
    let values = Object.values(el);
    sheet.getRow(4 + index).values = values;
  });

  let bgColor = "";
  let column = null;
  for (let i = 0; i < infoColumnNum; i++) {
    column = sheet.getColumn(i + 1);
    column.width = columnWidth[i] || 16.73;
    bgColor = i > infoColumnNum - 1 ? "C00000" : "FFFC574F";
    sheet.getCell(3, i + 1).fill = {
      type: "pattern",
      pattern: "solid",
      fgColor: { argb: bgColor }
    };
    sheet.getCell(3, i + 1).font = {
      color: { argb: "FFFFFFFF" },
      size: 12,
      bold: true
    };
  }
  // 控制所有单元格垂直水平居中
  sheet.eachRow(function (row, rowNumber) {
    row.alignment = {
      vertical: "middle",
      horizontal: "center"
    };
  });
  const EXCEL_TYPE =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
  const title = name;
  workbook.xlsx.writeBuffer().then(data => {
    const blob = new Blob([data], { type: EXCEL_TYPE });
    fileSaver.saveAs(blob, `${title}.xlsx`);
  });
}
